package com.learn.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.learn.entity.WechatMessage;
import com.learn.utils.WxUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/wx")
public class WeiXinController {
    @Autowired
    private WxUtils wxUtils;

    // 1. GET：用于首次接入验证（微信后台保存配置时调用）
    @GetMapping("/callback")
    public String verify(@RequestParam String echostr) {
        return echostr; // 必须原样返回 echostr
    }

    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public ResponseEntity<String> receiveMessage(@RequestBody WechatMessage msg) {
        try {
            System.out.println("OpenID: " + msg.getFromUserName());
            System.out.println("消息类型: " + msg.getMsgType());
            System.out.println("内容: " + msg.getContent());
            System.out.println("url: " + msg.getPicUrl());
            wxUtils.sendMessage(msg.getContent(),msg.getFromUserName());
            // 必须返回空字符串，否则微信认为失败并重试
            return ResponseEntity.ok("");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("");
        }


    }


}
